<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>RabbitMQ死信队列在SpringBoot中的使用 | 一只特立独行的猪^(*￣(oo)￣)^</title>
    <meta name="generator" content="VuePress 1.8.0">
    
    <meta name="description" content="一只特立独行的猪的分享">
    
    <link rel="preload" href="/press-blog/assets/css/0.styles.41d49717.css" as="style"><link rel="preload" href="/press-blog/assets/js/app.d4168a11.js" as="script"><link rel="preload" href="/press-blog/assets/js/2.8d6ea248.js" as="script"><link rel="preload" href="/press-blog/assets/js/8.780b8f13.js" as="script"><link rel="prefetch" href="/press-blog/assets/js/10.f7fbfdbe.js"><link rel="prefetch" href="/press-blog/assets/js/3.a7b40a35.js"><link rel="prefetch" href="/press-blog/assets/js/4.77a548c8.js"><link rel="prefetch" href="/press-blog/assets/js/5.5fd3c55b.js"><link rel="prefetch" href="/press-blog/assets/js/6.706caab8.js"><link rel="prefetch" href="/press-blog/assets/js/7.74938af9.js"><link rel="prefetch" href="/press-blog/assets/js/9.b3c9fa86.js">
    <link rel="stylesheet" href="/press-blog/assets/css/0.styles.41d49717.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/press-blog/" class="home-link router-link-active"><!----> <span class="site-name">一只特立独行的猪^(*￣(oo)￣)^</span></a> <div class="links"><!----> <nav class="nav-links can-hide"><div class="nav-item"><a href="/press-blog/" class="nav-link router-link-active">
  主页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="博文" class="dropdown-title"><span class="title">博文</span> <span class="arrow down"></span></button> <button type="button" aria-label="博文" class="mobile-dropdown-title"><span class="title">博文</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/press-blog/rabbitmq/delivery.html" class="nav-link">
  RabbitMQ
</a></li><li class="dropdown-item"><!----> <a href="/press-blog/multi-thread/" class="nav-link">
  多线程
</a></li><li class="dropdown-item"><!----> <a href="/press-blog/java/" class="nav-link">
  java
</a></li></ul></div></div><div class="nav-item"><a href="/press-blog/about/" class="nav-link">
  关于
</a></div><div class="nav-item"><a href="https://www.github.com/futaosmile" target="_blank" rel="noopener noreferrer" class="nav-link external">
  Github
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <!----></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/press-blog/" class="nav-link router-link-active">
  主页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="博文" class="dropdown-title"><span class="title">博文</span> <span class="arrow down"></span></button> <button type="button" aria-label="博文" class="mobile-dropdown-title"><span class="title">博文</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/press-blog/rabbitmq/delivery.html" class="nav-link">
  RabbitMQ
</a></li><li class="dropdown-item"><!----> <a href="/press-blog/multi-thread/" class="nav-link">
  多线程
</a></li><li class="dropdown-item"><!----> <a href="/press-blog/java/" class="nav-link">
  java
</a></li></ul></div></div><div class="nav-item"><a href="/press-blog/about/" class="nav-link">
  关于
</a></div><div class="nav-item"><a href="https://www.github.com/futaosmile" target="_blank" rel="noopener noreferrer" class="nav-link external">
  Github
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <!----></nav>  <ul class="sidebar-links"><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading open"><span>RabbitMQ</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/press-blog/rabbitmq/delivery.html" class="sidebar-link">SpringBoot RabbitMQ实现消息可靠投递</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/press-blog/rabbitmq/delivery.html#一、实现思路" class="sidebar-link">一、实现思路</a></li><li class="sidebar-sub-header"><a href="/press-blog/rabbitmq/delivery.html#二、准备-框架搭建" class="sidebar-link">二、准备，框架搭建</a></li><li class="sidebar-sub-header"><a href="/press-blog/rabbitmq/delivery.html#三、编码" class="sidebar-link">三、编码</a></li><li class="sidebar-sub-header"><a href="/press-blog/rabbitmq/delivery.html#四、测试" class="sidebar-link">四、测试</a></li><li class="sidebar-sub-header"><a href="/press-blog/rabbitmq/delivery.html#next" class="sidebar-link"># Next</a></li></ul></li><li><a href="/press-blog/rabbitmq/dead-letter.html" aria-current="page" class="active sidebar-link">RabbitMQ死信队列在SpringBoot中的使用</a><ul class="sidebar-sub-headers"></ul></li><li><a href="/press-blog/rabbitmq/expire.html" class="sidebar-link">使用RabbitMQ实现未支付订单在30分钟后自动过期</a><ul class="sidebar-sub-headers"></ul></li></ul></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>核心功能</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>扩展</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>插件</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>FAQ</span> <span class="arrow right"></span></p> <!----></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="rabbitmq死信队列在springboot中的使用"><a href="#rabbitmq死信队列在springboot中的使用" class="header-anchor">#</a> RabbitMQ死信队列在SpringBoot中的使用</h1> <blockquote><p>死信队列可以实现消息在未被正常消费的场景下，对这些消息进行其他处理，保证消息不会被丢弃。</p></blockquote> <h3 id="概念"><a href="#概念" class="header-anchor">#</a> # 概念：</h3> <ul><li><p><strong>消息会变成死信消息的场景：</strong></p> <ol><li>消息被<code>(basic.reject() or basic.nack()) and requeue = false</code>，即消息被消费者拒绝签收，并且重新入队为false。 1.1
有一种场景需要注意下：消费者设置了自动ACK，当重复投递次数达到了设置的最大retry次数之后，消息也会投递到死信队列，但是内部的原理还是调用了<code>nack</code>/<code>reject</code>。</li> <li>消息过期，过了TTL存活时间。</li> <li>队列设置了<code>x-max-length</code>最大消息数量且当前队列中的消息已经达到了这个数量，再次投递，消息将被挤掉，被挤掉的是最靠近被消费那一端的消息。</li></ol></li> <li><p><strong>代码编写流程是：</strong></p> <ol><li>有一个(n个)正常业务的Exchange，比如为<code>user-exchange</code>。</li> <li>有一个(n个)正常业务的Queue，比如为<code>user-queue</code>。（因为该队列需要绑定死信交换机，所以需要加俩参数：死信交换机:<code>x-dead-letter-exchange</code>
，死信消息路由键:<code>x-dead-letter-routing-key</code>）</li> <li>进行正常业务的交换机和队列绑定。</li> <li>定义一个死信交换机，比如为<code>common-dead-letter-exchange</code>。</li> <li>将正常业务的队列绑定到死信交换机(队列设置了<code>x-dead-letter-exchange</code>即会自动绑定)。</li> <li>定义死信队列<code>user-dead-letter-queue</code>用于接收死信消息，绑定死信交换机。</li></ol></li> <li><p><strong>业务流程是：</strong></p> <ol><li>正常业务消息被投递到正常业务的Exchange，该Exchange根据路由键将消息路由到绑定的正常队列。</li> <li>正常业务队列中的消息变成了死信消息之后，会被自动投递到该队列绑定的死信交换机上（并带上配置的路由键，如果没有指定死信消息的路由键，则默认继承该消息在正常业务时设定的路由键）。</li> <li>死信交换机收到消息后，将消息根据路由规则路由到指定的死信队列。</li> <li>消息到达死信队列后，可监听该死信队列，处理死信消息。</li></ol></li> <li><p><code>死信交换机</code>、<code>死信队列</code>也是普通的交换机和队列，只不过是我们人为的将某个交换机和队列来处理死信消息。</p></li> <li><p>流程图</p></li></ul> <p><img src="https://upload-images.jianshu.io/upload_images/1846623-b8a539f6cc06c1ab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图片.png"></p> <h3 id="代码实现"><a href="#代码实现" class="header-anchor">#</a> # 代码实现</h3> <ol><li>配置</li></ol> <div class="language-yml line-numbers-mode"><pre class="language-yml"><code><span class="token key atrule">spring</span><span class="token punctuation">:</span>
  <span class="token key atrule">application</span><span class="token punctuation">:</span>
    <span class="token key atrule">name</span><span class="token punctuation">:</span> learn<span class="token punctuation">-</span>rabbitmq
  <span class="token key atrule">rabbitmq</span><span class="token punctuation">:</span>
    <span class="token key atrule">host</span><span class="token punctuation">:</span> localhost
    <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token number">5672</span>
    <span class="token key atrule">username</span><span class="token punctuation">:</span> futao
    <span class="token key atrule">password</span><span class="token punctuation">:</span> <span class="token number">123456789</span>
    <span class="token key atrule">virtual-host</span><span class="token punctuation">:</span> deadletter<span class="token punctuation">-</span>vh
    <span class="token key atrule">connection-timeout</span><span class="token punctuation">:</span> <span class="token number">15000</span>
    <span class="token comment"># 发送确认</span>
    <span class="token key atrule">publisher-confirms</span><span class="token punctuation">:</span> <span class="token boolean important">true</span>
    <span class="token comment"># 路由失败回调</span>
    <span class="token key atrule">publisher-returns</span><span class="token punctuation">:</span> <span class="token boolean important">true</span>
    <span class="token key atrule">template</span><span class="token punctuation">:</span>
      <span class="token comment"># 必须设置成true 消息路由失败通知监听者，而不是将消息丢弃</span>
      <span class="token key atrule">mandatory</span><span class="token punctuation">:</span> <span class="token boolean important">true</span>
    <span class="token key atrule">listener</span><span class="token punctuation">:</span>
      <span class="token key atrule">simple</span><span class="token punctuation">:</span>
        <span class="token comment"># 每次从RabbitMQ获取的消息数量</span>
        <span class="token key atrule">prefetch</span><span class="token punctuation">:</span> <span class="token number">1</span>
        <span class="token key atrule">default-requeue-rejected</span><span class="token punctuation">:</span> <span class="token boolean important">false</span>
        <span class="token comment"># 每个队列启动的消费者数量</span>
        <span class="token key atrule">concurrency</span><span class="token punctuation">:</span> <span class="token number">1</span>
        <span class="token comment"># 每个队列最大的消费者数量</span>
        <span class="token key atrule">max-concurrency</span><span class="token punctuation">:</span> <span class="token number">1</span>
        <span class="token comment"># 签收模式为手动签收-那么需要在代码中手动ACK</span>
        <span class="token key atrule">acknowledge-mode</span><span class="token punctuation">:</span> manual

<span class="token key atrule">app</span><span class="token punctuation">:</span>
  <span class="token key atrule">rabbitmq</span><span class="token punctuation">:</span>
    <span class="token comment"># 队列定义</span>
    <span class="token key atrule">queue</span><span class="token punctuation">:</span>
      <span class="token comment"># 正常业务队列</span>
      <span class="token key atrule">user</span><span class="token punctuation">:</span> user<span class="token punctuation">-</span>queue
      <span class="token comment"># 死信队列</span>
      <span class="token key atrule">user-dead-letter</span><span class="token punctuation">:</span> user<span class="token punctuation">-</span>dead<span class="token punctuation">-</span>letter<span class="token punctuation">-</span>queue
    <span class="token comment"># 交换机定义</span>
    <span class="token key atrule">exchange</span><span class="token punctuation">:</span>
      <span class="token comment"># 正常业务交换机</span>
      <span class="token key atrule">user</span><span class="token punctuation">:</span> user<span class="token punctuation">-</span>exchange
      <span class="token comment"># 死信交换机</span>
      <span class="token key atrule">common-dead-letter</span><span class="token punctuation">:</span> common<span class="token punctuation">-</span>dead<span class="token punctuation">-</span>letter<span class="token punctuation">-</span>exchange
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br></div></div><ol start="2"><li>队列、交换机定义与绑定。</li></ol> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">/**
 * 队列与交换机定义与绑定
 *
 * @author futao
 * @date 2020/4/7.
 */</span>
<span class="token annotation punctuation">@Configuration</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Declare</span> <span class="token punctuation">{</span>

    <span class="token comment">/**
     * 用户队列
     *
     * @param userQueueName 用户队列名
     * @return
     */</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">Queue</span> <span class="token function">userQueue</span><span class="token punctuation">(</span><span class="token annotation punctuation">@Value</span><span class="token punctuation">(</span><span class="token string">&quot;${app.rabbitmq.queue.user}&quot;</span><span class="token punctuation">)</span> <span class="token class-name">String</span> userQueueName<span class="token punctuation">,</span>
                           <span class="token annotation punctuation">@Value</span><span class="token punctuation">(</span><span class="token string">&quot;${app.rabbitmq.exchange.common-dead-letter}&quot;</span><span class="token punctuation">)</span> <span class="token class-name">String</span> commonDeadLetterExchange<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">QueueBuilder</span>
                <span class="token punctuation">.</span><span class="token function">durable</span><span class="token punctuation">(</span>userQueueName<span class="token punctuation">)</span>
                <span class="token comment">//声明该队列的死信消息发送到的 交换机 （队列添加了这个参数之后会自动与该交换机绑定，并设置路由键，不需要开发者手动设置)</span>
                <span class="token punctuation">.</span><span class="token function">withArgument</span><span class="token punctuation">(</span><span class="token string">&quot;x-dead-letter-exchange&quot;</span><span class="token punctuation">,</span> commonDeadLetterExchange<span class="token punctuation">)</span>
                <span class="token comment">//声明该队列死信消息在交换机的 路由键</span>
                <span class="token punctuation">.</span><span class="token function">withArgument</span><span class="token punctuation">(</span><span class="token string">&quot;x-dead-letter-routing-key&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;user-dead-letter-routing-key&quot;</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/**
     * 用户交换机
     *
     * @param userExchangeName 用户交换机名
     * @return
     */</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">Exchange</span> <span class="token function">userExchange</span><span class="token punctuation">(</span><span class="token annotation punctuation">@Value</span><span class="token punctuation">(</span><span class="token string">&quot;${app.rabbitmq.exchange.user}&quot;</span><span class="token punctuation">)</span> <span class="token class-name">String</span> userExchangeName<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">ExchangeBuilder</span>
                <span class="token punctuation">.</span><span class="token function">topicExchange</span><span class="token punctuation">(</span>userExchangeName<span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">durable</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/**
     * 用户队列与交换机绑定
     *
     * @param userQueue    用户队列名
     * @param userExchange 用户交换机名
     * @return
     */</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">Binding</span> <span class="token function">userBinding</span><span class="token punctuation">(</span><span class="token class-name">Queue</span> userQueue<span class="token punctuation">,</span> <span class="token class-name">Exchange</span> userExchange<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">BindingBuilder</span>
                <span class="token punctuation">.</span><span class="token function">bind</span><span class="token punctuation">(</span>userQueue<span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token keyword">to</span><span class="token punctuation">(</span>userExchange<span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token keyword">with</span><span class="token punctuation">(</span><span class="token string">&quot;user.*&quot;</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">noargs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/**
     * 死信交换机
     *
     * @param commonDeadLetterExchange 通用死信交换机名
     * @return
     */</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">Exchange</span> <span class="token function">commonDeadLetterExchange</span><span class="token punctuation">(</span><span class="token annotation punctuation">@Value</span><span class="token punctuation">(</span><span class="token string">&quot;${app.rabbitmq.exchange.common-dead-letter}&quot;</span><span class="token punctuation">)</span> <span class="token class-name">String</span> commonDeadLetterExchange<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">ExchangeBuilder</span>
                <span class="token punctuation">.</span><span class="token function">topicExchange</span><span class="token punctuation">(</span>commonDeadLetterExchange<span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">durable</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>


    <span class="token comment">/**
     * 用户队列的死信消息 路由的队列
     * 用户队列user-queue的死信投递到死信交换机`common-dead-letter-exchange`后再投递到该队列
     * 用这个队列来接收user-queue的死信消息
     *
     * @return
     */</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">Queue</span> <span class="token function">userDeadLetterQueue</span><span class="token punctuation">(</span><span class="token annotation punctuation">@Value</span><span class="token punctuation">(</span><span class="token string">&quot;${app.rabbitmq.queue.user-dead-letter}&quot;</span><span class="token punctuation">)</span> <span class="token class-name">String</span> userDeadLetterQueue<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">QueueBuilder</span>
                <span class="token punctuation">.</span><span class="token function">durable</span><span class="token punctuation">(</span>userDeadLetterQueue<span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/**
     * 死信队列绑定死信交换机
     *
     * @param userDeadLetterQueue      user-queue对应的死信队列
     * @param commonDeadLetterExchange 通用死信交换机
     * @return
     */</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">Binding</span> <span class="token function">userDeadLetterBinding</span><span class="token punctuation">(</span><span class="token class-name">Queue</span> userDeadLetterQueue<span class="token punctuation">,</span> <span class="token class-name">Exchange</span> commonDeadLetterExchange<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">BindingBuilder</span>
                <span class="token punctuation">.</span><span class="token function">bind</span><span class="token punctuation">(</span>userDeadLetterQueue<span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token keyword">to</span><span class="token punctuation">(</span>commonDeadLetterExchange<span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token keyword">with</span><span class="token punctuation">(</span><span class="token string">&quot;user-dead-letter-routing-key&quot;</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">noargs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br><span class="line-number">44</span><br><span class="line-number">45</span><br><span class="line-number">46</span><br><span class="line-number">47</span><br><span class="line-number">48</span><br><span class="line-number">49</span><br><span class="line-number">50</span><br><span class="line-number">51</span><br><span class="line-number">52</span><br><span class="line-number">53</span><br><span class="line-number">54</span><br><span class="line-number">55</span><br><span class="line-number">56</span><br><span class="line-number">57</span><br><span class="line-number">58</span><br><span class="line-number">59</span><br><span class="line-number">60</span><br><span class="line-number">61</span><br><span class="line-number">62</span><br><span class="line-number">63</span><br><span class="line-number">64</span><br><span class="line-number">65</span><br><span class="line-number">66</span><br><span class="line-number">67</span><br><span class="line-number">68</span><br><span class="line-number">69</span><br><span class="line-number">70</span><br><span class="line-number">71</span><br><span class="line-number">72</span><br><span class="line-number">73</span><br><span class="line-number">74</span><br><span class="line-number">75</span><br><span class="line-number">76</span><br><span class="line-number">77</span><br><span class="line-number">78</span><br><span class="line-number">79</span><br><span class="line-number">80</span><br><span class="line-number">81</span><br><span class="line-number">82</span><br><span class="line-number">83</span><br><span class="line-number">84</span><br><span class="line-number">85</span><br><span class="line-number">86</span><br><span class="line-number">87</span><br><span class="line-number">88</span><br><span class="line-number">89</span><br><span class="line-number">90</span><br><span class="line-number">91</span><br><span class="line-number">92</span><br><span class="line-number">93</span><br><span class="line-number">94</span><br><span class="line-number">95</span><br><span class="line-number">96</span><br><span class="line-number">97</span><br><span class="line-number">98</span><br><span class="line-number">99</span><br><span class="line-number">100</span><br><span class="line-number">101</span><br><span class="line-number">102</span><br><span class="line-number">103</span><br></div></div><ul><li>定义好之后启动程序，springboot会读取Spring容器中类型为Queue和Exchange的bean进行队列和交换机的初始化与绑定。当然也可以自己在RabbitMQ的管理后台进行手动创建与绑定。</li> <li>查看管理后台
<img src="https://upload-images.jianshu.io/upload_images/1846623-fd80f618867e862c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="交换机"> <img src="https://upload-images.jianshu.io/upload_images/1846623-f0848f8ab30d2461.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="队列"> <img src="https://upload-images.jianshu.io/upload_images/1846623-5bd40c2ee141dbde.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="队列与死信交换机"></li></ul> <h3 id="测试"><a href="#测试" class="header-anchor">#</a> # 测试</h3> <ul><li>消息生产者</li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">/**
 * @author futao
 * @date 2020/4/7.
 */</span>
<span class="token annotation punctuation">@Component</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DeadLetterSender</span> <span class="token punctuation">{</span>

    <span class="token annotation punctuation">@Autowired</span>
    <span class="token keyword">private</span> <span class="token class-name">RabbitTemplate</span> rabbitTemplate<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Value</span><span class="token punctuation">(</span><span class="token string">&quot;${app.rabbitmq.exchange.user}&quot;</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> userExchange<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">User</span> user <span class="token operator">=</span> <span class="token class-name">User</span><span class="token punctuation">.</span><span class="token function">builder</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">userName</span><span class="token punctuation">(</span><span class="token string">&quot;天文&quot;</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">address</span><span class="token punctuation">(</span><span class="token string">&quot;浙江杭州&quot;</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">birthday</span><span class="token punctuation">(</span><span class="token class-name">LocalDate</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token class-name">ZoneOffset</span><span class="token punctuation">.</span><span class="token function">ofHours</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        rabbitTemplate<span class="token punctuation">.</span><span class="token function">convertAndSend</span><span class="token punctuation">(</span>userExchange<span class="token punctuation">,</span> <span class="token string">&quot;user.abc&quot;</span><span class="token punctuation">,</span> user<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br></div></div><p><strong>1. 场景1.1</strong></p> <blockquote><p>消息被(basic.reject() or basic.nack()) and requeue = false，即消息被消费者拒绝或者nack，并且重新入队为false。</p></blockquote> <p><em>nack()与reject()的区别是：reject()不支持批量拒绝，而nack()可以.</em></p> <ul><li>消费者代码</li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">/**
 * @author futao
 * @date 2020/4/9.
 */</span>
<span class="token annotation punctuation">@Slf4j</span>
<span class="token annotation punctuation">@Component</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Consumer</span> <span class="token punctuation">{</span>

    <span class="token comment">/**
     * 正常用户队列消息监听消费者
     *
     * @param user
     * @param message
     * @param channel
     */</span>
    <span class="token annotation punctuation">@RabbitListener</span><span class="token punctuation">(</span>queues <span class="token operator">=</span> <span class="token string">&quot;${app.rabbitmq.queue.user}&quot;</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">userConsumer</span><span class="token punctuation">(</span><span class="token class-name">User</span> user<span class="token punctuation">,</span> <span class="token class-name">Message</span> message<span class="token punctuation">,</span> <span class="token class-name">Channel</span> channel<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">&quot;正常用户业务监听：接收到消息:[{}]&quot;</span><span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>user<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            <span class="token comment">//参数为：消息的DeliveryTag，是否批量拒绝，是否重新入队</span>
            channel<span class="token punctuation">.</span><span class="token function">basicNack</span><span class="token punctuation">(</span>message<span class="token punctuation">.</span><span class="token function">getMessageProperties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getDeliveryTag</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">&quot;拒绝签收...消息的路由键为:[{}]&quot;</span><span class="token punctuation">,</span> message<span class="token punctuation">.</span><span class="token function">getMessageProperties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getReceivedRoutingKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">&quot;消息拒绝签收失败&quot;</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/**
     * @param user
     * @param message
     * @param channel
     */</span>
    <span class="token annotation punctuation">@RabbitListener</span><span class="token punctuation">(</span>queues <span class="token operator">=</span> <span class="token string">&quot;${app.rabbitmq.queue.user-dead-letter}&quot;</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">userDeadLetterConsumer</span><span class="token punctuation">(</span><span class="token class-name">User</span> user<span class="token punctuation">,</span> <span class="token class-name">Message</span> message<span class="token punctuation">,</span> <span class="token class-name">Channel</span> channel<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">&quot;接收到死信消息:[{}]&quot;</span><span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>user<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            channel<span class="token punctuation">.</span><span class="token function">basicAck</span><span class="token punctuation">(</span>message<span class="token punctuation">.</span><span class="token function">getMessageProperties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getDeliveryTag</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">&quot;死信队列签收消息....消息路由键为:[{}]&quot;</span><span class="token punctuation">,</span> message<span class="token punctuation">.</span><span class="token function">getMessageProperties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getReceivedRoutingKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">&quot;死信队列消息签收失败&quot;</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br></div></div><ul><li>可以看到，正常消息被NACK之后最后到了死信队列，且路由键发生了变化。
<img src="https://upload-images.jianshu.io/upload_images/1846623-30339960bb86d3d6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="死信消息"> <strong>1. 场景1.2</strong></li></ul> <blockquote><p>消费者设置了自动签收，当重复投递次数达到了设置的最大retry次数之后，消息也会投递到死信队列，但是内部的原理还是调用了<code>nack</code>/<code>reject</code>。</p></blockquote> <ul><li>application.yml中需要更改一些配置</li></ul> <div class="language-yml line-numbers-mode"><pre class="language-yml"><code><span class="token key atrule">spring</span><span class="token punctuation">:</span>
  <span class="token key atrule">application</span><span class="token punctuation">:</span>
    <span class="token key atrule">name</span><span class="token punctuation">:</span> learn<span class="token punctuation">-</span>rabbitmq
  <span class="token key atrule">rabbitmq</span><span class="token punctuation">:</span>
    <span class="token key atrule">listener</span><span class="token punctuation">:</span>
      <span class="token key atrule">simple</span><span class="token punctuation">:</span>
        <span class="token comment"># 每次从RabbitMQ获取的消息数量</span>
        <span class="token key atrule">prefetch</span><span class="token punctuation">:</span> <span class="token number">1</span>
        <span class="token key atrule">default-requeue-rejected</span><span class="token punctuation">:</span> <span class="token boolean important">false</span>
        <span class="token comment"># 每个队列启动的消费者数量</span>
        <span class="token key atrule">concurrency</span><span class="token punctuation">:</span> <span class="token number">1</span>
        <span class="token comment"># 每个队列最大的消费者数量</span>
        <span class="token key atrule">max-concurrency</span><span class="token punctuation">:</span> <span class="token number">1</span>
        <span class="token comment"># 自动签收</span>
        <span class="token key atrule">acknowledge-mode</span><span class="token punctuation">:</span> auto
        <span class="token key atrule">retry</span><span class="token punctuation">:</span>
          <span class="token key atrule">enabled</span><span class="token punctuation">:</span> <span class="token boolean important">true</span>
          <span class="token comment"># 第一次尝试时间间隔</span>
          <span class="token key atrule">initial-interval</span><span class="token punctuation">:</span> 10S
          <span class="token comment"># 两次尝试之间的最长持续时间。</span>
          <span class="token key atrule">max-interval</span><span class="token punctuation">:</span> 10S
          <span class="token comment"># 最大重试次数(=第一次正常投递1+重试次数4)</span>
          <span class="token key atrule">max-attempts</span><span class="token punctuation">:</span> <span class="token number">5</span>
          <span class="token comment"># 上一次重试时间的乘数</span>
          <span class="token key atrule">multiplier</span><span class="token punctuation">:</span> <span class="token number">1.0</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br></div></div><ul><li>消费者代码</li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">/**
 * @author futao
 * @date 2020/4/9.
 */</span>
<span class="token annotation punctuation">@Slf4j</span>
<span class="token annotation punctuation">@Configuration</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">AutoAckConsumer</span> <span class="token punctuation">{</span>

    <span class="token comment">/**
     * 正常用户队列消息监听消费者
     *
     * @param user
     */</span>
    <span class="token annotation punctuation">@RabbitListener</span><span class="token punctuation">(</span>queues <span class="token operator">=</span> <span class="token string">&quot;${app.rabbitmq.queue.user}&quot;</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">userConsumer</span><span class="token punctuation">(</span><span class="token class-name">User</span> user<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">&quot;正常用户业务监听：接收到消息:[{}]&quot;</span><span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>user<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span><span class="token string">&quot;模拟发生异常&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/**
     * @param user
     */</span>
    <span class="token annotation punctuation">@RabbitListener</span><span class="token punctuation">(</span>queues <span class="token operator">=</span> <span class="token string">&quot;${app.rabbitmq.queue.user-dead-letter}&quot;</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">userDeadLetterConsumer</span><span class="token punctuation">(</span><span class="token class-name">User</span> user<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">&quot;接收到死信消息并自动签收:[{}]&quot;</span><span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>user<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br></div></div><ul><li><p>测试结果：
<img src="https://upload-images.jianshu.io/upload_images/1846623-d8cff1c53ecb63e2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"> <img src="https://upload-images.jianshu.io/upload_images/1846623-fcd8abe8c66ccb22.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p></li> <li><p>从测试结果可以看出，消息如果未被正常消费，则进行重试，如果最终还未被正常消费，则会被投递到死信队列。</p></li></ul> <p><em><code>initial-interval</code>,<code>max-interval</code>这两个参数啥作用不知道，现在测试的结果是一直都会取最短的那个时间作为下次投递时间...</em></p> <p><strong>2. 测试场景 2</strong></p> <blockquote><p>消息过期，过了TTL存活时间。</p></blockquote> <ul><li>需要修改队列定义，设置队列消息的过期时间<code>x-message-ttl</code>.</li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code>    <span class="token comment">/**
 * 用户队列
 *
 * @param userQueueName 用户队列名
 * @return
 */</span>
<span class="token annotation punctuation">@Bean</span>
<span class="token keyword">public</span> <span class="token class-name">Queue</span> <span class="token function">userQueue</span><span class="token punctuation">(</span><span class="token annotation punctuation">@Value</span><span class="token punctuation">(</span><span class="token string">&quot;${app.rabbitmq.queue.user}&quot;</span><span class="token punctuation">)</span> <span class="token class-name">String</span> userQueueName<span class="token punctuation">,</span>
<span class="token annotation punctuation">@Value</span><span class="token punctuation">(</span><span class="token string">&quot;${app.rabbitmq.exchange.common-dead-letter}&quot;</span><span class="token punctuation">)</span> <span class="token class-name">String</span> commonDeadLetterExchange<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">QueueBuilder</span>
        <span class="token punctuation">.</span><span class="token function">durable</span><span class="token punctuation">(</span>userQueueName<span class="token punctuation">)</span>
        <span class="token comment">//声明该队列的死信消息发送到的 交换机 （队列添加了这个参数之后会自动与该交换机绑定，并设置路由键，不需要开发者手动设置)</span>
        <span class="token punctuation">.</span><span class="token function">withArgument</span><span class="token punctuation">(</span><span class="token string">&quot;x-dead-letter-exchange&quot;</span><span class="token punctuation">,</span>commonDeadLetterExchange<span class="token punctuation">)</span>
        <span class="token comment">//声明该队列死信消息在交换机的 路由键</span>
        <span class="token punctuation">.</span><span class="token function">withArgument</span><span class="token punctuation">(</span><span class="token string">&quot;x-dead-letter-routing-key&quot;</span><span class="token punctuation">,</span><span class="token string">&quot;user-dead-letter-routing-key&quot;</span><span class="token punctuation">)</span>
        <span class="token comment">//该队列的消息的过期时间-超过这个时间还未被消费则路由到死信队列</span>
        <span class="token punctuation">.</span><span class="token function">withArgument</span><span class="token punctuation">(</span><span class="token string">&quot;x-message-ttl&quot;</span><span class="token punctuation">,</span><span class="token number">5000</span><span class="token punctuation">)</span>
        <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br></div></div><ul><li><p>把<code>user-queue</code>的消费者注释，使消息无法被消费，直到消息在队列中的时间达到设定的存活时间。
<img src="https://upload-images.jianshu.io/upload_images/1846623-a058a703f04a94dd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="ttl"></p></li> <li><p>根据日志可以看到，消息在5S后会被投递到死信队列。
<img src="https://upload-images.jianshu.io/upload_images/1846623-ddbfc38d38706101.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p></li> <li><p><strong>注意：可以给队列设置消息过期时间，那么所有投递到这个队列的消息都自动具有这个属性。还可以在消息投递之前，给每条消息设定指定的过期时间。（当两者都设置了，则默认取较短的值）</strong></p></li></ul> <p><strong>下面测试给每条消息设置指定的过期时间：</strong></p> <ul><li>修改消息生产者：</li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">/**
 * @author futao
 * @date 2020/4/7.
 */</span>
<span class="token annotation punctuation">@Slf4j</span>
<span class="token annotation punctuation">@Component</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DeadLetterSender</span> <span class="token punctuation">{</span>

    <span class="token annotation punctuation">@Autowired</span>
    <span class="token keyword">private</span> <span class="token class-name">RabbitTemplate</span> rabbitTemplate<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Value</span><span class="token punctuation">(</span><span class="token string">&quot;${app.rabbitmq.exchange.user}&quot;</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> userExchange<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">send</span><span class="token punctuation">(</span><span class="token class-name">String</span> exp<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">User</span> user <span class="token operator">=</span> <span class="token class-name">User</span><span class="token punctuation">.</span><span class="token function">builder</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">userName</span><span class="token punctuation">(</span><span class="token string">&quot;天文&quot;</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">address</span><span class="token punctuation">(</span><span class="token string">&quot;浙江杭州&quot;</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">birthday</span><span class="token punctuation">(</span><span class="token class-name">LocalDate</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token class-name">ZoneOffset</span><span class="token punctuation">.</span><span class="token function">ofHours</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">&quot;消息投递...指定的存活时长为:[{}]ms&quot;</span><span class="token punctuation">,</span> exp<span class="token punctuation">)</span><span class="token punctuation">;</span>
        rabbitTemplate<span class="token punctuation">.</span><span class="token function">convertAndSend</span><span class="token punctuation">(</span>userExchange<span class="token punctuation">,</span> <span class="token string">&quot;user.abc&quot;</span><span class="token punctuation">,</span> user<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">MessagePostProcessor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token class-name">Message</span> <span class="token function">postProcessMessage</span><span class="token punctuation">(</span><span class="token class-name">Message</span> message<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">AmqpException</span> <span class="token punctuation">{</span>
                <span class="token class-name">MessageProperties</span> messageProperties <span class="token operator">=</span> message<span class="token punctuation">.</span><span class="token function">getMessageProperties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token comment">//为每条消息设定过期时间</span>
                messageProperties<span class="token punctuation">.</span><span class="token function">setExpiration</span><span class="token punctuation">(</span>exp<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">return</span> message<span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br></div></div><p><img src="https://upload-images.jianshu.io/upload_images/1846623-6360d971a4ffe7e0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p> <ul><li>从测试结果可以看出，每条消息都在指定的时间投递到了死信队列。</li></ul> <p><strong>【坑】重点注意!!!
：RabbitMQ对于消息过期的检测：只会检测最近将要被消费的那条消息是否到达了过期时间，不会检测非末端消息是否过期。造成的问题是：非末端消息已经过期了，但是因为末端消息还未过期，非末端消息处于阻塞状态，所以非末端消息不会被检测到已经过期。使业务产生与预期严重不一致的结果。</strong></p> <ul><li>对上面的问题进行测试：(第一条消息的过期时间设置成10S，第二条消息设置成5S)
<img src="https://upload-images.jianshu.io/upload_images/1846623-e070e176458d206b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></li> <li>从测试结果可以看出，id为1的消息存活时长为10S，id为2的消息存活时间为5S。但是只有当第一条消息（id=1）过期之后，id=2的消息到达队列末端，才会被检测到已经过期。</li></ul> <p><strong>3. 测试场景3</strong></p> <blockquote><p>队列设置了<code>x-max-length</code>最大消息数量且当前队列中的消息已经达到了这个数量，再次投递，消息将被挤掉，被挤掉的是最靠近被消费那一端的消息。</p></blockquote> <ul><li>修改队列定义</li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code>  <span class="token comment">/**
 * 用户队列
 *
 * @param userQueueName 用户队列名
 * @return
 */</span>
<span class="token annotation punctuation">@Bean</span>
<span class="token keyword">public</span> <span class="token class-name">Queue</span> <span class="token function">userQueue</span><span class="token punctuation">(</span><span class="token annotation punctuation">@Value</span><span class="token punctuation">(</span><span class="token string">&quot;${app.rabbitmq.queue.user}&quot;</span><span class="token punctuation">)</span> <span class="token class-name">String</span> userQueueName<span class="token punctuation">,</span>
<span class="token annotation punctuation">@Value</span><span class="token punctuation">(</span><span class="token string">&quot;${app.rabbitmq.exchange.common-dead-letter}&quot;</span><span class="token punctuation">)</span> <span class="token class-name">String</span> commonDeadLetterExchange<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token class-name">QueueBuilder</span>
        <span class="token punctuation">.</span><span class="token function">durable</span><span class="token punctuation">(</span>userQueueName<span class="token punctuation">)</span>
        <span class="token comment">//声明该队列的死信消息发送到的 交换机 （队列添加了这个参数之后会自动与该交换机绑定，并设置路由键，不需要开发者手动设置)</span>
        <span class="token punctuation">.</span><span class="token function">withArgument</span><span class="token punctuation">(</span><span class="token string">&quot;x-dead-letter-exchange&quot;</span><span class="token punctuation">,</span>commonDeadLetterExchange<span class="token punctuation">)</span>
        <span class="token comment">//声明该队列死信消息在交换机的 路由键</span>
        <span class="token punctuation">.</span><span class="token function">withArgument</span><span class="token punctuation">(</span><span class="token string">&quot;x-dead-letter-routing-key&quot;</span><span class="token punctuation">,</span><span class="token string">&quot;user-dead-letter-routing-key&quot;</span><span class="token punctuation">)</span>
        <span class="token comment">//队列最大消息数量</span>
        <span class="token punctuation">.</span><span class="token function">withArgument</span><span class="token punctuation">(</span><span class="token string">&quot;x-max-length&quot;</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">)</span>
        <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br></div></div><p><img src="https://upload-images.jianshu.io/upload_images/1846623-180870b475b5f0f3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p> <ul><li><p>向队列中投递消息
<img src="https://upload-images.jianshu.io/upload_images/1846623-773347aff2aef108.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p></li> <li><p>从结果可以看出，当投递第3条消息的时候，RabbitMQ会把在最靠经被消费那一端的消息移出队列，并投递到死信队列。
<img src="https://upload-images.jianshu.io/upload_images/1846623-0fc287e9c61680fd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png">
队列中将始终保持最多两个消息。</p></li></ul> <h3 id="其他"><a href="#其他" class="header-anchor">#</a> # 其他：</h3> <ul><li>Queue的可配置项可在RabbitMQ的管理后台查看：
<img src="https://upload-images.jianshu.io/upload_images/1846623-52de0ad194d9f6ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></li> <li></li></ul> <p>源码：<a href="https://github.com/FutaoSmile/springboot-learn-integration/tree/master/springboot-learn-rabbitmq" target="_blank" rel="noopener noreferrer">https://github.com/FutaoSmile/springboot-learn-integration/tree/master/springboot-learn-rabbitmq<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p> <h3 id="相关"><a href="#相关" class="header-anchor">#</a> # 相关:</h3> <p><a href="https://www.jianshu.com/p/432167bbe95f" target="_blank" rel="noopener noreferrer">SpringBoot RabbitMQ实现消息可靠投递
<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p> <h3 id="todo"><a href="#todo" class="header-anchor">#</a> # TODO：</h3> <ul><li>消费端限流保护</li> <li>延迟队列</li></ul></div> <footer class="page-edit"><!----> <!----></footer> <!----> </main></div><div class="global-ui"></div></div>
    <script src="/press-blog/assets/js/app.d4168a11.js" defer></script><script src="/press-blog/assets/js/2.8d6ea248.js" defer></script><script src="/press-blog/assets/js/8.780b8f13.js" defer></script>
  </body>
</html>
